package com.marquis.cloud.filter;

import com.marquis.cloud.common.Constants;
import com.marquis.cloud.common.JWTResult;
import com.marquis.cloud.common.JWTUtils;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class AuthFilter implements Filter {

    /**
     * 拦截器初始化
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 拦截器业务处理
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        //此处可对请求方法进行刷选
        String uri = request.getRequestURI();
        if (!uri.contains("login")) {
            String token = request.getHeader(Constants.X_TOKEN);
            //token令牌检查
            JWTResult jr = JWTUtils.checkToken(token);
            if(!jr.isStatus()){
                //令牌不正确
                response.getWriter().write(jr.getMsg());
                return;
            }else {
                List<String> pers = new ArrayList<>();
                pers.add("/aut/user/query");
                pers.add("/aut/user/queryUserPage");
                boolean flag = false;
                for (String per : pers) {
                    if(!"/".equals(per.substring(0,1))){
                        per = "/" + per;
                    }
                    if(uri.equals(per)){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    response.getWriter().write("没有权限访问");
                    return;
                }
            }
        }
        //请求继续执行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 拦截器销毁
     */
    @Override
    public void destroy() {

    }
}
